package com.xixi.exp2.config;

import com.xixi.exp2.bean.MyBean;
import com.xixi.exp2.listener.MyCommandLineRunner;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.boot.CommandLineRunner;
import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty;
import org.springframework.boot.context.properties.EnableConfigurationProperties;
import org.springframework.context.ApplicationEvent;
import org.springframework.context.ApplicationListener;
import org.springframework.context.annotation.Bean;
import org.springframework.context.event.ApplicationEventMulticaster;
import org.springframework.context.event.SimpleApplicationEventMulticaster;
import org.springframework.context.support.AbstractApplicationContext;
import org.springframework.scheduling.concurrent.ThreadPoolTaskExecutor;
import org.springframework.stereotype.Component;

@EnableConfigurationProperties(MyBean.class)
public class MyAutoConfig {
    @Bean
    @ConditionalOnProperty(prefix = "xixi.config", name = "id", havingValue = "201741412115")
    CommandLineRunner createMyCommandLineRunner(){
        return new MyCommandLineRunner();
    }

    @Bean(AbstractApplicationContext.APPLICATION_EVENT_MULTICASTER_BEAN_NAME)
    ApplicationEventMulticaster applicationEventMulticaster(ThreadPoolTaskExecutor taskExecutor)
    {
        SimpleApplicationEventMulticaster multicaster = new SimpleApplicationEventMulticaster();
        multicaster.setTaskExecutor(taskExecutor);
        return multicaster;
    }

    public static class MyNoticeEvent extends ApplicationEvent{
        private static final Logger logger = LoggerFactory.getLogger(MyNoticeEvent.class);
        private final String msg;
        public MyNoticeEvent(String msg) {
            super(msg);
            this.msg = msg;
            logger.info("添加事件成功：" + msg);
        }

        public String getMsg() {
            return msg;
        }
    }

    @Component
    static class MyNoticeListener implements ApplicationListener<MyNoticeEvent> {
        private static final Logger loggger = LoggerFactory.getLogger(MyNoticeListener.class);
        @Override
        public void onApplicationEvent(MyNoticeEvent myNoticeEvent) {
            loggger.info("事件监听器获取到MyNoticeEvent，当前线程睡眠5秒...");
            try{
                Thread.sleep(5000);
            }catch (Exception e)
            {
                e.printStackTrace();
            }
            loggger.info("MyNoticeEvent的 msg = " + myNoticeEvent.getMsg());
        }
    }
}
